import axios from "axios";
import qs from "qs";
import { message } from "antd";
import { createHashHistory } from "history";
const history = createHashHistory();
const request = axios.create({
  baseURL: "/api/v1",
  timeout: 8000,
});

// 加拦截
let hide = null;
// 请求拦截
request.interceptors.request.use(
  function (config) {
    // 处理token
    hide = message.loading("加载中...", 0);
    const userInfo = localStorage.getItem("userInfo")
      ? JSON.parse(localStorage.getItem("userInfo"))
      : {};
    const token = userInfo.token;
    if (token) {
      config.headers["access_token"] = token;
    }
    if (config.method === "post" && config.data) {
      config.data = qs.stringify(config.data);
    }

    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截
request.interceptors.response.use(
  function (res) {
    /* 
  处理token过期  401
  处理其他问题  

  */
    if (res.data.code === 401) {
      message.error("token过期了，请重新登录");
      //  跳转到登录
      history.push("/login");
      history.go(0);
    }
    hide();
    return res;
  },
  function (error) {
    return Promise.reject(error);
  }
);

export default request;
